﻿using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace RDPManager
{
    class RdpClient
    {
        // 控制页面
        public TabPage Page;
        // 连接名
        string Name;
        // 连接IP
        string IP;
        // 连接用户名
        string Username;
        // 连接密码
        string Password;
        // rdp客户端
        AxMSTSCLib.AxMsRdpClient8NotSafeForScripting Client;

        public RdpClient(TabControl control, SingleConfig singleConfig)
        {
            Name = singleConfig.Name;
            IP = singleConfig.IP;
            Username = singleConfig.Username;
            Password = singleConfig.Password;

            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RdpClient));
            Page = new TabPage();
            Client = new AxMSTSCLib.AxMsRdpClient8NotSafeForScripting()
            {
                Dock = DockStyle.Fill
            };

            // 添加新页签到TabControl
            Page.Name = Name + "(" + IP + ")";
            Page.Text = Name + "(" + IP + ")";
            Page.Controls.Add(Client);
            control.Controls.Add(Page);
            control.SelectedTab = Page;
        }

        // 尝试连接
        public bool TryConnect()
        {
            Ping pingsender = new Ping();
            PingReply reply = pingsender.Send(IP.Trim());//判断输入的ip是否合法
            if (reply.Status == IPStatus.Success)
            {
                Client.Server = IP.Trim();//远程桌面IP地址
                Client.AdvancedSettings2.RDPPort = 3389;//远程连接端口，默认是3389
                Client.UserName = Username.Trim();//远程连接用户名
                Client.AdvancedSettings5.ClearTextPassword = Password.Trim();

                Client.GetOcx();
                Client.AdvancedSettings9.EnableCredSspSupport = true;
                Client.Connect();
                Client.Show();
                return true;
            }
            else
            {
                MessageBox.Show("远程连接失败!");
                return false;
            }
        }
    }
}
